package controllers

import (
	"encoding/xml"
	"fmt"
	"github.com/revel/revel"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
	"wuhuaguo.com/whg01/app/utils"
)

type Order struct {
	WxApp
}

func (o Order) Index(orderid string) revel.Result {
	user := o.wxId()
	cost := 0.5
	return o.Render(user, cost)
}

func (o Order) CommitOrder(itemids string) revel.Result {
	orderid := utils.OrderId()

	return o.RenderText("/wx/pay/order?id=" + orderid)
}

//微信支付接口调用返回结构

/*
<xml><return_code><![CDATA[SUCCESS]]></return_code>
<return_msg><![CDATA[OK]]></return_msg>
<appid><![CDATA[wx05054be971d87487]]></appid>
<mch_id><![CDATA[1482507442]]></mch_id>
<nonce_str><![CDATA[MuvvNHLKr7YUEZTg]]></nonce_str>
<sign><![CDATA[5171AD0F2E53BE09561FA79487C6D52E]]></sign>
<result_code><![CDATA[SUCCESS]]></result_code>
<prepay_id><![CDATA[wx20170902172811c85988d7980696359004]]></prepay_id>
<trade_type><![CDATA[JSAPI]]></trade_type>
</xml>
*/
type PayInfo struct {
}

// 微信客户端调用该路径进入支付目录，生成支付界面， 用户点击上面的支付按钮 页面调用微信的支付接口
// 调用微信统一下单接口https://api.mch.weixin.qq.com/pay/unifiedorder
/*
@ category  商品类目
@ price 元， 需要转成分

//需要返回nonce_str   sign

*/

type resp struct {
	Return_code int
	Nonce_str   string
	Sign        string
	Prepay_id   string
	TimeStamp   string
}

func (c Order) DoPay(category string, price float64, orderid string) revel.Result {
	mch_id := "1482507442"
	appid := "wx05054be971d87487"
	nonce_str := utils.Random32str()
	apikey := "9a7ae5b8e7bb38d491425e928bc4efg0"
	body := "无花果官网-" + category
	out_trade_no := orderid
	total_fee := int(price * 100)
	spbill_create_ip := c.ip()
	notify_url := "http://117bm.cn/wx/pay/callback"
	trade_type := "JSAPI"
	openid := c.wxId().Wxopenid

	stringA := fmt.Sprintf("appid=%s&body=%s&mch_id=%s&nonce_str=%s&notify_url=%s&openid=%s&out_trade_no=%s&spbill_create_ip=%s&total_fee=%d&trade_type=%s",
		appid, body, mch_id, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee, trade_type)
	stringSignTemp := stringA + "&key=" + apikey

	sign := utils.MD5(stringSignTemp)

	var content string = fmt.Sprintf(
		`<xml>
	   <appid>%s</appid>
	   <body>%s</body>
	   <mch_id>%s</mch_id>
	   <nonce_str>%s</nonce_str>
	   <notify_url>%s</notify_url>
	   <openid>%s</openid>
	   <out_trade_no>%s</out_trade_no>
	   <spbill_create_ip>%s</spbill_create_ip>
	   <total_fee>%d</total_fee>
	   <trade_type>%s</trade_type>
	   <sign>%s</sign>
	</xml>`, appid, body, mch_id, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee, trade_type, sign)

	body_reader := strings.NewReader(content)
	req, err := http.NewRequest("POST", "https://api.mch.weixin.qq.com/pay/unifiedorder", body_reader)
	client := http.DefaultClient

	rsp, err := client.Do(req)
	if err != nil {
		fmt.Println(err.Error())
	}

	b, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		fmt.Println(err.Error())
	}
	pi := &payinfo{}
	err = xml.Unmarshal(b, pi)
	if err != nil {
		fmt.Println(err.Error())
		return c.RenderJson(&resp{Return_code: 1})
	}
	r := &resp{
		Return_code: 0,
		Nonce_str:   pi.Nonce_str,
		Prepay_id:   pi.Prepay_id,
		TimeStamp:   fmt.Sprintf("%d", time.Now().Unix()),
	}
	genSign(r)

	return c.RenderJson(r)
}

func genSign(r *resp) {
	appid := "wx05054be971d87487"
	apikey := "9a7ae5b8e7bb38d491425e928bc4efg0"
	stringA := fmt.Sprintf("appId=%s&nonceStr=%s&package=prepay_id=%s&signType=MD5&timeStamp=%s",
		appid, r.Nonce_str, r.Prepay_id, r.TimeStamp)
	stringSignTemp := stringA + "&key=" + apikey
	fmt.Println(stringSignTemp)
	sign := utils.MD5(stringSignTemp)
	fmt.Println(sign)
	r.Sign = sign
}

/*
<xml><return_code><![CDATA[SUCCESS]]></return_code>
<return_msg><![CDATA[OK]]></return_msg>
<appid><![CDATA[wx05054be971d87487]]></appid>
<mch_id><![CDATA[1482507442]]></mch_id>
<nonce_str><![CDATA[rCH0TeMEATu57rZ1]]></nonce_str>
<sign><![CDATA[875602292DD686F20C1B75E3DB013EC6]]></sign>
<result_code><![CDATA[SUCCESS]]></result_code>
<prepay_id><![CDATA[wx20170918220704049339e9e80993236487]]></prepay_id>
<trade_type><![CDATA[JSAPI]]></trade_type>
</xml>
*/

type payinfo struct {
	Return_code string `xml:"return_code"`
	Return_msg  string `xml:"return_msg"`
	Appid       string `xml:"appid"`
	Mch_id      string `xml:"mch_id"`
	Nonce_str   string `xml:"nonce_str"`
	Sign        string `xml:"sign"`
	Result_code string `xml:"result_code"`
	Prepay_id   string `xml:"prepay_id"`
	Trade_type  string `xml:"trade_type"`
}

func (w Order) PayNotify() revel.Result {

	fmt.Println(w.Request)
	b, err := ioutil.ReadAll(w.Request.Body)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println(string(b))
	return nil
}
